define(function (require, exports, module) {
    var $ = require('jquery');
    var jquery = require('jquery');
    require('rangyinputs');
    var _ = require('underscore');
    require('underscore.string');
    var AjaxManager = require('./ajaxManager').AjaxManager;
    var DeliveryBlacklist = require('./deliveryBlacklist').DeliveryBlacklist;
    var Mustache = require('Mustache');
    var Modal = require('./modal').Modal;
    var Tabs = require('./tabs').Tabs;
    var MAX_CUSTOM_TPL = 2;

    function DeliveryService () {
        var that = this;

        this.container = $('#delivery');

        this.modal = null;

        this.tabs = null;

        this.tabContentTplDataArr = [];

        this.navArr = [];

        this.container.find('.sm-content').each(function (index) {
            var $this = $(this);
            var content = _.str.trim($this.html());
            var trimmed;

            if (content.length > 64) {
                trimmed = content.substr(0, 62) + '...';
                $this.prop('title', content);
                $this.html(trimmed);
            } else {
                $this.html(content);
            }
        });

        this.container.find('.mod').each(function (index) {
            that.navArr.push({
                label: $(this).find('.mod-hd h4').html()
            });
        });

        this.container.delegate('.tip', 'click', function (ev) {
            ev.preventDefault();

            window.serviceTabs.switchTo(2);
        });

        // switch buttons click event handling
        this.container.find('.switch-btn').each(function (index) {
            $(this).click(function (ev) {
                var switchBtn = $(this);
                var serviceId = that.tabContentTplDataArr[index].serviceId;
                var userId = $(document.body).attr('data-userid');
                var $serviceSwitch = $('#home-services .service-switch').eq(index);

                ev.preventDefault();

                if (switchBtn.parents('.mod').hasClass('mod-active')) {
                    AjaxManager.send('closeDeliveryNotifyService', {
                        serviceId: serviceId,
                        userId: userId
                    }, function (result) {
                        var $tip = switchBtn.parents('.btn-wrap').next('.tip');

                        if (result.success) {
                            if ($tip.length) {
                                $tip.hide();
                            }
                            switchBtn
                                .parents('.mod')
                                .removeClass('mod-active')
                                .end()
                                .html('立即开启');
                            $serviceSwitch.removeClass('service-switch-on');
                            $serviceSwitch.find('.service-status').html('未开启');
                        }
                    });
                } else {
                    AjaxManager.send('openDeliveryNotifyService', {
                        serviceId: serviceId,
                        userId: userId
                    }, function (result) {
                        var $tip = switchBtn.parents('.btn-wrap').next('.tip');

                        if (result.success) {
                            if ($tip.length) {
                                $tip.hide();
                            }
                            switchBtn
                                .parents('.mod')
                                .addClass('mod-active')
                                .end()
                                .html('已开启');
                            $serviceSwitch.addClass('service-switch-on');
                            $serviceSwitch.find('.service-status').html('已开启');
                        } else {
                            if ($tip.length) {
                                $tip.show();
                            } else {
                                // todo
                                $tip = $('<p class="tip">您的短信余额不足。<a href="#page-wrap" target="_blank">立即充值</a></p>')
                                    .insertAfter(switchBtn.parents('.btn-wrap'));
                            }
                        }
                    });
                }
            });
        });

        // edit short messages setting
        this.container.find('.setting-btn').each(function (index) {
            $(this).click(function (ev) {
                ev.preventDefault();

                that.tabs.switchTo(index);

                that.modal.show();
            });
        });

        this._initializeModal();
    }

    DeliveryService.prototype._initializeModal = function () {
        var that = this;

        this.modal = new Modal('#delivery-modal');

        this.modal.container.find('.modal-wrap').html(Mustache.render($('#delivery-modal-tpl').html(), {
            navArr: this.navArr
        }));

        this.tabs = new Tabs(this.modal.container.find('.modal-hd .tabs-navs'), this.modal.container.find('.modal-bd'));

        $.each(this.navArr, function (index, value) {
            var tabContentTplData = {};
            var $tabContent = that.tabs.get('contents').eq(index);

            tabContentTplData.userId = $(document.body).attr('data-userid');
            tabContentTplData.serviceId = $tabContent.attr('data-serviceid');
            tabContentTplData.queryApi = $tabContent.attr('data-query');
            tabContentTplData.updateApi = $tabContent.attr('data-update');
            tabContentTplData.tplArr = DeliveryService.getTplArr($tabContent.attr('data-tpl'));

            that.tabContentTplDataArr[index] = tabContentTplData;
        });


        this.tabs.on('change:activeIndex', function (activeIndex) {
            if (activeIndex == that.tabs.get('contents').length - 1) {
                new DeliveryBlacklist(that.tabs.get('contents').eq(activeIndex));
            } else {
                that.queryTabContent(activeIndex);
            }
        });

        this.tabs.render(-1);
    };

    DeliveryService.prototype.updateModal = function (index, data) {
        var that = this;
        var customTplArr = [];
        var $content = this.tabs.get('contents').eq(index);

        // get custom templates
        $.each(DeliveryService.getTplArr(data.customTpls), function (index, value) {
            customTplArr.push({
                index: index + 1,
                value: value
            });
        });

        data.customTplArr = customTplArr;
        //
        if (customTplArr.length > MAX_CUSTOM_TPL) {
            customTplArr.length = MAX_CUSTOM_TPL;
        }

        if (customTplArr.length == MAX_CUSTOM_TPL) {
            data.showAddBtn = false;
        } else {
            data.showAddBtn = true;
        }

        // render modal template
        $content.find('.sm-template').html(Mustache.render($('#delivery-sm-tpl').html(), data));

        // template radios
        $content.find('.sm-template-list li').each(function (index) {
            var $this = $(this);
            var input = $this.find('input');
            var label = $this.find('label');

            input.prop('id', 'sm-template-' + index);
            input.val(index);
            label.prop('htmlFor', 'sm-template-' + index);

            if ($this.hasClass('custom-tpl')) {
                that.initializeCustomTplOption($this);

                if ($this.find('textarea').val() == data.tpl) {
                    input.prop('checked', true);
                }
            } else {
                if (label.html() == data.tpl) {
                    input.prop('checked', true);
                }
            }
        });

        // add btn
        if (customTplArr.length < MAX_CUSTOM_TPL) {
            $content.find('.sm-template-add a').click(function (ev) {
                var $this = $(this);

                var data = {
                    value: '',
                    index: customTplArr.length
                };

                var container = $('<li>').html(Mustache.render($('#delivery-custom-tpl').html(), data)).addClass('custom-tpl');

                ev.preventDefault();

                that.modal.container.find('.sm-template-list').children().append(container);

                customTplArr.push(data);

                if (customTplArr.length == MAX_CUSTOM_TPL) {
                    $this.parents('.sm-template-add').hide();
                }

                that.initializeCustomTplOption(container);
            });
        }

        $content.find('.btn-save').click(function (ev) {
            var tabContentTplData = _.extend({}, that.tabContentTplDataArr[index]);
            var tpl;
            var customTplArr = [];
            var $form = $(this).parents('form');

            ev.preventDefault();

            $form.find('textarea').each(function (index) {
                var $textarea = $(this);
                var tpl = _.str.trim($textarea.val());

                if (tpl != '') {
                    customTplArr.push(encodeURIComponent(tpl));
                }
            });

            tabContentTplData.customTpls = customTplArr.join(';;');

            $form.find('.input-radio').each(function (index) {
                var $radio = $(this);
                var $li;

                if ($radio.prop('checked')) {
                    $li = $radio.parents('li');

                    if ($li.hasClass('custom-tpl')) {
                        tpl = _.str.trim($li.find('textarea').val());
                    } else {
                        tpl = _.str.trim($li.find('label').html());
                    }

                    tabContentTplData.tpl = encodeURIComponent(tpl);
                    return false;
                }
            });

            tabContentTplData.condition = $form.prop('condition').value;
            tabContentTplData.shopName = $form.prop('shop').value;

            AjaxManager.send(tabContentTplData.updateApi, tabContentTplData, function (result) {
                var trimmed;
                var $content;

                if (result.success) {
                    that.modal.hide();

                    if (tpl != '') {
                        $content = $('#delivery .mod .sm-content').eq(index);

                        if (tpl.length > 64) {
                            trimmed = tpl.substr(0, 62) + '...';
                            $content.prop('title', tpl);
                            $content.html(trimmed);
                        } else {
                            $content.html(tpl);
                        }
                    }
                }
            });
        });

        $content.find('form').prop('condition').value = data.condition;
        $content.find('form').prop('shop').value = data.shopName;

        this.tabs.switchTo(index);

        this.modal.show();
    };

    DeliveryService.prototype.initializeCustomTplOption = function (container) {
        var textarea;
        var counter = container.find('.counter .figure');
        var selectedPlaceholder = '';
        var isTextareaFocused = false;

        textarea = container.find('textarea')
            .focus(function () {
                isTextareaFocused = true;
            })
            .blur(function (ev) {
                var selection;

                if (selectedPlaceholder) {
                    ev.preventDefault();

                    selection = textarea.getSelection();

                    if (selection.length > 0) {
                        textarea.replaceSelectedText(selectedPlaceholder);
                    } else {
                        textarea.insertText(selectedPlaceholder, selection.start, 'collapseToEnd');
                    }

                    counter.html(textarea.val().length);

                    selectedPlaceholder = '';
                } else {
                    isTextareaFocused = false;
                }
            })
            .keyup(function (ev) {
                counter.html(textarea.val().length);
            });

        container.find('.custom-tpl-placeholders').delegate('a', 'mousedown',function (ev) {
            var placeholder = $(this).html();

            if (!isTextareaFocused) {
                textarea.focus().insertText(placeholder, textarea.val().length - 1, 'collapseToEnd');
                counter.html(textarea.val().length);
            } else {
                selectedPlaceholder = placeholder;
            }
        }).delegate('a', 'click', function (ev) {
                ev.preventDefault();
            });

        counter.html(textarea.val().length);
    };

    DeliveryService.getTplArr = function (str) {
        var valid = /^(;;)?([^;]+(;;[^;]+)*)(;;)?$/.test(str);
        var arr = [];

        if (valid) {
            $.each(str.split(';;'), function (index, value) {
                if (value != '') {
                    arr.push(value);
                }
            });
        }

        return arr;
    };

    DeliveryService.validate = function (str) {
        return /^;?([^,;]+(;[^,;]+)*);?$/.test(str);
    };

    DeliveryService.prototype.queryTabContent = function (index) {
        var that = this;

        AjaxManager.send(this.tabContentTplDataArr[index].queryApi, {
            userId: $(document.body).attr('data-userid')
        }, function (result) {
            that.updateModal(index, _.extend({}, that.tabContentTplDataArr[index], result));
        });
    };

    DeliveryService.trimSmTpl = function (tpl) {
    };

    exports.DeliveryService = DeliveryService;
});